package com.dq.annotation.aop.aspect;

import com.dq.annotation.aop.DataFilter;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.service.ShiroService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 数据过滤，切面处理类
 */
@Aspect
@Component
public class DataFilterAspect {
    @Autowired
    private ShiroService shiroService;

    /**
     * 切点
     */
    @Pointcut("@annotation(com.dq.annotation.aop.DataFilter)")
    public void dataFilterCut() {

    }

    /**
     * 前置通知
     * 所属机构筛选
     *
     * @param point 连接点
     */
    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) throws AdminException {
        //获取参数
        Object params = point.getArgs()[0];
        if (params instanceof BaseAdminQuery) {
            MethodSignature signature = (MethodSignature) point.getSignature();
            DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);

            String deptAlias = dataFilter.deptAlias();
            if (!shiroService.isSuperAdmin()) {
                if (StringUtils.isNotBlank(deptAlias) && "org".equals(deptAlias)) {
                    ((BaseAdminQuery) params).setSection(shiroService.getDept());
                } else {
                    ((BaseAdminQuery) params).setSection(shiroService.getDept());
                }
            }
            return;
        }
        throw new AdminException("数据权限接口的参数必须为Map类型，且不能为NULL");
    }
}
